//
//  M4FirstInfoViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit
import KakaJSON

class M4FirstInfoViewController: M4BaseViewController, UITextFieldDelegate {
    
    private var m4educationData: [M4InfoItemListModel] = []
    private var m4marryData: [M4InfoItemListModel] = []
    private var m4workData: [M4InfoItemListModel] = []
    private var m4incomeData: [M4InfoItemListModel] = []
    private var m4relationshipData: [M4InfoItemListModel] = []
    private var titles = ["Nivel educativo", "Estado civil", "Provincia o ciudad actual", "Tipo de trabajo", "Rango salarial"]
    
    private var m4province: M4ProvinceCityModel?
    private var m4city: M4ProvinceCityModel?
    private var m4enterTime: Int = 0
    var dropDownMenu: M4EmailDropUpMenue!
    var originalMenuData = ["@gmail.com","@outlook.cl","@outlook.com","@yahoo.com",
                            "@yahoo.com.cl","@yahoo.cl","@Aahoo.com",
                            "@aim.com","@aol.com","@Email.com",
                            "@hotmail.cl","@hotmail.com","@inbox.com","@live.com","@mail.com",
                            "@msn.com","@rediffmail.com","@vahoo.cl","@walla.com"]
    
    let emailTFTag = 101
    var filteredMenuData: [String] = []
    
    var GASQ = 0
    
    lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .white
        scroll.contentSize.width = M4ScreenWidth
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        return scroll
    }()
    
    lazy var tipImageView: M4InfosTopKycTipImageView = {
       
        
        
        let view = UINib(nibName: "M4InfosTopKycTipImageView", bundle: nil).instantiate(withOwner: self).last as! M4InfosTopKycTipImageView
        view.M4TipimageView.image = UIImage(named: "img_schedule1")
        
        view.setStyledCreditText(amountText: "$ 16,000",typestr: 1)
        return view
    }()
    
    lazy var bottomView: M4InfosBottomView = {
        let view = M4InfosBottomView()
        view.m4View.c = self
        view.m4BottomButtonBlock = { button in
            //提交信息
//            let vc = M4SecondInfoViewController()
//            self.navigationController?.pushViewController(vc, animated: true)
//            button.M4EventUnavailable = false
            self.view.endEditing(true)
            self.M4SubmitFirstInfoNet()
        }
        return view
    }()
    
    private var m4inputTFViews: [M4InfosPublicView] = []
    
    var addressData: (String, Int, Int) = ("", 0, 0)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        self.view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Información personal", M4NavTitleColor: COLOR_333333)
        M4ItemInfoNet()
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        M4InfosPageBack()
        sender.M4EventUnavailable = false
        
        self.uploadData()
    }
    
    private func m4updateUI() {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        scrollView.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
        if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //==1
            titles.append("Correo electrónico")
        }
        for i in 0..<titles.count {
            let view = UINib(nibName: "M4InfosPublicView", bundle: nil).instantiate(withOwner: self).last as! M4InfosPublicView
            view.m4InfoPublicTitle.text = titles[i]
            view.m4InfoPublicTF.isUserInteractionEnabled = false
            if (i == 2){
                view.m4InfoPublicTF.tag = 10001
            }
            view.tag = i
            m4inputTFViews.append(view)
            scrollView.addSubview(view)
            view.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.height.equalTo(85)
                make.top.equalTo(tipImageView.snp.bottom).offset(85*i)
                make.width.equalTo(M4ScreenWidth)
            }
            if i == titles.count - 1 {
                if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //== 1
                    view.m4InfoPublicTF.isUserInteractionEnabled = true
                    view.m4InfoPublicTF.delegate = self
                    view.m4InfoPublicTF.tag = emailTFTag
                    view.m4InfoPublicDownIcon.isHidden = true
                    view.m4InfoPublicDownRight.constant = 0
                    view.m4InfoPublicDownWidth.constant = 0
                    view.m4InfoPublicTF.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
                    
                    dropDownMenu = M4EmailDropUpMenue(frame: CGRect.zero, data: originalMenuData, targetView: view.m4InfoPublicTF)
                    dropDownMenu.isHidden = true
                    view.addSubview(dropDownMenu)
                }
                else {
                    view.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                                     action: #selector(M4ItemTap(gesture:))))
                }
                scrollView.addSubview(bottomView)
                bottomView.snp.makeConstraints { make in
                    make.top.equalTo(view.snp.bottom).offset(20)
                    make.left.right.equalToSuperview()
                    make.bottom.equalToSuperview().offset(-20)
                    make.width.equalTo(M4ScreenWidth)
                }
            }
            else {
                view.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                                 action: #selector(M4ItemTap(gesture:))))
            }
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textString = textField.text else {return true}
        let length = textString.count + string.count - range.length
        if string == " " ||  length > 80 {
            return false
        }
        return true
    }
    
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 3001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "GASQ" : GASQ
            ],
            [
                "adga" : 3002,
                "afqwe" : addressData.0,
                "akgjrt" : addressData.2 - addressData.1,
            ],
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .Personal, paramsKey: "Fqwe", params: params, complete: nil)
    }
}

extension M4FirstInfoViewController {
    
    @objc private func M4ItemTap(gesture: UITapGestureRecognizer) {
        view.endEditing(true)
        let tag = gesture.view?.tag ?? 0
        M4ItemViewShow(tag: tag)
    }
    
    private func M4AtomicShowInfoView(tag: Int) {
        var m4tag = tag
        if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //== 1
            if m4tag == m4inputTFViews.count-2 {
                m4tag = 0
            }
            for i in m4tag..<m4inputTFViews.count-1 {
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    M4ItemViewShow(tag: i)
                    break
                }
            }
        }
        else {
            if m4tag == m4inputTFViews.count-1 {
                m4tag = 0
            }
            for i in m4tag..<m4inputTFViews.count {
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    M4ItemViewShow(tag: i)
                    break
                }
            }
        }
    }
    
    private func M4ItemViewShow(tag: Int) {
        if tag == 2 {
            print("------provice-----")
            M4ProvinceCityNet(tag: tag)
        }
        else {
            var itemData: [M4InfoItemListModel] = []
            if tag == 0 {
                itemData = m4educationData
            }
            else if tag == 1 {
                itemData = m4marryData
            }
            else if tag == 3 {
                itemData = m4workData
            }
            else if tag == 4 {
                itemData = m4incomeData
            }
            let listView = UINib(nibName: "M4InfosListAlertView", bundle: nil).instantiate(withOwner: self).last as! M4InfosListAlertView
            listView.M4InfosListUpdateUI(title: titles[tag], data: itemData)
            listView.M4SelectedInfoReturn = { chooseString in
                self.m4inputTFViews[tag].m4InfoPublicTF.text = chooseString
                self.M4AtomicShowInfoView(tag: tag)
            }
            if m4inputTFViews[tag].m4InfoPublicTF.text?.count != 0 {
                for k in 0..<listView.M4CellData.count {
                    let str = listView.M4CellData[k].GTG
                    if str == m4inputTFViews[tag].m4InfoPublicTF.text {
                        listView.M4SelectedIndex = k
                        break
                    }
                }
            }
            listView.M4PopViewShow(subview: listView.M4InfosListBGView)
        }
    }
    
}

extension M4FirstInfoViewController {
    @objc func textFieldDidChange(_ textField: UITextField) {
        if textField.tag == emailTFTag {
            if ((textField.text?.count) != 0) {
                dropDownMenu.isHidden = false
                let inputStr = textField.text ?? ""
                if inputStr.contains("@") {
                    var searchTextStr = ""
                    if let lastPart = inputStr.components(separatedBy: "@").last {
                        searchTextStr = "@" + lastPart
                    }
                    showDropDownMenu(for: textField, searchText:searchTextStr)
                }
                
            } else {
                dropDownMenu.isHidden = true
                filteredMenuData = []
                dropDownMenu.data = originalMenuData
            }
        }
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        
        if textField.tag == emailTFTag,let text = textField.text, !text.isEmpty {
            let Y : CGFloat = M4NavigationFullHeight() + 290
            dropDownMenu.showMenu(from: textField,X: 16,Y: Y, width: M4ScreenWidth - 32,height: 300, didSelectItemHandler: { selectedItem in
                let inputString = textField.text ?? ""
                if inputString.contains("@") {
                    if let firstPart = inputString.components(separatedBy: "@").first {
                        textField.text = firstPart + selectedItem
                        if let text = textField.text {
                            //                            let trimmedText = text.trimmingCharacters(in: .whitespaces)
                            let trimmedText = text.replacingOccurrences(of: " ", with: "")
                            textField.text = trimmedText
                        }
                    }
                }else{
                    textField.text = text + selectedItem
                    if let text = textField.text {
                        let trimmedText = text.replacingOccurrences(of: " ", with: "")
                        textField.text = trimmedText
                    }
                }
                self.dropDownMenu.hideMenu()
            })
        } else {
            dropDownMenu.hideMenu()
        }
    }
    
    
    func showDropDownMenu(for textField: UITextField, searchText: String) {
        let menuData = searchText.isEmpty ? originalMenuData : originalMenuData.filter { $0.localizedCaseInsensitiveContains(searchText) }
        
        if !menuData.isEmpty {
            dropDownMenu.data = menuData
            let Y : CGFloat = M4NavigationFullHeight() + 290
            dropDownMenu.showMenu(from: textField,X: 16,Y: Y, width: M4ScreenWidth - 32,height: CGFloat(menuData.count) * cellHeight, didSelectItemHandler: { selectedItem in
                let _ = searchText.replacingOccurrences(of: searchText, with: selectedItem)
                let inputString = textField.text ?? ""
                if inputString.contains("@") {
                    if let firstPart = inputString.components(separatedBy: "@").first {
                        textField.text = firstPart + selectedItem
                        if let text = textField.text {
                            let trimmedText = text.replacingOccurrences(of: " ", with: "")
                            textField.text = trimmedText
                        }
                    }
                }else{
                    textField.text = inputString + selectedItem
                    if let text = textField.text {
                        let trimmedText = text.replacingOccurrences(of: " ", with: "")
                        textField.text = trimmedText
                    }
                }
                
                self.dropDownMenu.hideMenu()
            })
        } else {
            dropDownMenu.hideMenu()
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.tag == 10001 {
            addressData.1 = Int(Date().timeIntervalSince1970 * 1000)

        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("email:\(textField.tag)")
        if textField.tag == emailTFTag {
            emailTextFieldEndEdit()
        }
        addressData.0 = textField.text ?? ""
        if textField.tag == 10001 {
            addressData.2 = Int(Date().timeIntervalSince1970 * 1000)

        }
    }
    
    @objc func emailTextFieldEndEdit() {
        dropDownMenu.hideMenu()
    }
    
}

extension M4FirstInfoViewController {
    
    private func M4ItemInfoNet() {
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4creditItemInfo, .post, params: ["LVsoN": "ESP", "WWR": M4UserDataManager.m4UserShare.M4Itemcode])) { model in
            if model.code == 1 {
                self.GASQ = 1
                let data = model.data as? [String : Any]
                let education = data?["Mfqb"] as? [[String : Any]]
                let marry = data?["Zchnx"] as? [[String : Any]]
                let work = data?["GatrBqom"] as? [[String : Any]]
                let income = data?["UoLvMAykrN"] as? [[String : Any]]
                let relationship = data?["LtrTCz"] as? [[String : Any]]
                self.m4educationData = education?.kj.modelArray(M4InfoItemListModel.self) ?? []
                self.m4marryData = marry?.kj.modelArray(M4InfoItemListModel.self) ?? []
                self.m4workData = work?.kj.modelArray(M4InfoItemListModel.self) ?? []
                self.m4incomeData = income?.kj.modelArray(M4InfoItemListModel.self) ?? []
                self.m4relationshipData = relationship?.kj.modelArray(M4InfoItemListModel.self) ?? []
                self.m4updateUI()
                self.M4ItemViewShow(tag: 0)
            }
            else {
                self.GASQ = 0
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4ProvinceCityNet(tag: Int) {
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4provicecity, .post, params: ["GxYcbFCkhB": M4UserDataManager.m4UserShare.M4Itemcode, "FWdm": "ESP", "HXr": M4UserDataManager.m4UserShare.M4Token])) { model in
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let province = data?["YNscR"] as? [[String : Any]]
                let provinceModel = province?.kj.modelArray(M4ProvinceCityModel.self) ?? []
                let city = data?["LVAzmZnsQT"] as? [[String : Any]]
                let cityModel = city?.kj.modelArray(M4ProvinceCityModel.self) ?? []
                let provinView = UINib(nibName: "M4InfosProvinceView", bundle: nil).instantiate(withOwner: self).last as! M4InfosProvinceView
                provinView.M4UpdateViewUI(title: self.titles[tag], model: (provinceModel, cityModel))
                provinView.M4ProvinCityBlock = { p, c in
                    self.m4inputTFViews[tag].m4InfoPublicTF.text = "\(p?.HYYXEhEZ ?? "") \(c?.HYYXEhEZ ?? "")"
                    self.m4province = p
                    self.m4city = c
                    self.M4AtomicShowInfoView(tag: tag)
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4SubmitFirstInfoNet() {
        self.bottomView.m4submitButton.M4EventUnavailable = false
        for i in 0..<m4inputTFViews.count {
            if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 && i == m4inputTFViews.count - 1 { //==1
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    self.view.makeToast("*No debe dejarse en blanco, introdúzcalo", position: .center)
                    self.bottomView.m4submitButton.M4EventUnavailable = false
                    return
                }
                if !isValidEmail(m4inputTFViews[i].m4InfoPublicTF.text ?? "") {
                    self.view.makeToast("*Introduzca la dirección de correo electrónico correcta", position: .center)
                    self.bottomView.m4submitButton.M4EventUnavailable = false
                    return
                }
            }
            else {
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    self.view.makeToast("Seleccione{\(titles[i])}", position: .center)
                    self.bottomView.m4submitButton.M4EventUnavailable = false
                    return
                }
            }
        }
        let m4submitTime: Int = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        var param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 11, "MrAavSrhrC": m4province?.ZySZN ?? "0", "GcnkGKIZC": m4city?.ZySZN ?? "0", "SHsg": m4submitTime]
        m4educationData.forEach { item in
            if item.GTG == m4inputTFViews[0].m4InfoPublicTF.text {
                param1["Wso"] = item.IfSps
            }
        }
        m4marryData.forEach { item in
            if item.GTG == m4inputTFViews[1].m4InfoPublicTF.text {
                param1["OrB"] = item.IfSps
            }
        }
        m4workData.forEach { item in
            if item.GTG == m4inputTFViews[3].m4InfoPublicTF.text {
                param1["HoWO"] = item.IfSps
            }
        }
        m4incomeData.forEach { item in
            if item.GTG == m4inputTFViews[4].m4InfoPublicTF.text {
                param1["Bgl"] = item.IfSps
            }
        }
        if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //==1
            param1["McUpKAV"] = m4inputTFViews[5].m4InfoPublicTF.text
        }
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.bottomView.m4submitButton.M4EventUnavailable = false
            if model.code == 1 {
                self.uploadData()
                let vc = M4SecondInfoViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func isValidEmail(_ email: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    }
    
}
